package com.tl.libpay.ui;

import android.os.Message;

import com.tl.commonlibrary.event.EventUtil;
import com.tl.commonlibrary.network.ErrorResponse;
import com.tl.commonlibrary.network.RequestListener;
import com.tl.commonlibrary.network.bean.base.BaseBean;
import com.tl.commonlibrary.tool.CountDownTimer;
import com.tl.commonlibrary.tool.UIUtils;
import com.tl.commonlibrary.ui.BaseFragmentActivity;
import com.tl.commonlibrary.ui.beans.AliPayBean;
import com.tl.commonlibrary.ui.beans.AliPayResultBean;
import com.tl.commonlibrary.ui.beans.WxPayOrderInfoBean;
import com.tl.libmanager.PayEntrance;
import com.tl.libpay.ali.PayAli;
import com.tl.libpay.network.Net;
import com.tl.libpay.wx.PayWX;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import retrofit2.Call;

public class PayTool extends PayEntrance.PayListener implements PayModeListener, CountDownTimer.OnCountDownListener {
    public static final String PAY_ALI_SUCCESS = "9000";
    public static final String PAY_WX_SUCCESS = "0";
    public static final String PAY_ABC_SUCCESS = "0";
    private BaseFragmentActivity activity;
    protected String wxTradeNo;
    private String aliPayResultCode = "";
    private String wxPayResultCode = "";
    private String abcPayResultCode = "";
    //    private String aliPayBean;//
    private AliPayBean aliPayBean;
    private CountDownTimer timer;
    protected PayEntrance.OnPayResultListener resultListener;
    private String productId;
    private int payWay;

    public PayTool(BaseFragmentActivity activity) {
        this.activity = activity;
        timer = new CountDownTimer(3000);
        timer.setOnCountDownListener(this);
    }

    public void setProductId(String productId) {
        this.productId = productId;
    }

    public void setResultListener(PayEntrance.OnPayResultListener resultListener) {
        this.resultListener = resultListener;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void wxEvent(WXPayEvent wxPayEvent) {
        unRegisterWXEvent();
        onWXPayResult(wxPayEvent.getCode(), wxPayEvent.getMessage());
    }

    @Override
    public void onSuccess(int type) {
        switch (type) {
            case PayHelper.PAY_TYPE_WX://微信
                onWXPayResult(PAY_WX_SUCCESS, "success");
                break;
            case PayHelper.PAY_TYPE_ALI://阿里
                onAliPayResult(PAY_ALI_SUCCESS, "success");
                break;
            case PayHelper.PAY_TYPE_ABC://农行
                onABCPayResult(PAY_ABC_SUCCESS, "success");
                break;
            default:
                break;
        }
    }

    @Override
    public void onFailed(int type, String message, String code) {
        switch (type) {
            case PayHelper.PAY_TYPE_WX://微信
                onWXPayResult(code, message);
//                unRegisterWXEvent();
                break;
            case PayHelper.PAY_TYPE_ALI://阿里
                onAliPayResult(code, message);
                break;
            case PayHelper.PAY_TYPE_ABC://农行
                onABCPayResult(code, message);
                break;
            default:
                break;
        }
    }

    @Override
    public void onAliPay() {
        activity.showProgressDialog();
        this.payWay = PayHelper.PAY_TYPE_ALI;
        Net.aliPay(productId, new RequestListener<BaseBean<AliPayBean>>() {
            @Override
            public void onSuccess(Call<BaseBean<AliPayBean>> call, BaseBean<AliPayBean> response) {
                aliPayBean = response.data;
                new PayAli(activity).pay(aliPayBean.getOrderString(), PayTool.this);
                activity.dismissAll();
            }

            @Override
            public void onFailed(Call<BaseBean<AliPayBean>> call, ErrorResponse errorResponse) {
                activity.dismissAll();
            }
        });
    }

    @Override
    public void onWXPay() {
        activity.showProgressDialog();
        this.payWay = PayHelper.PAY_TYPE_WX;
        Net.wechatPay(productId, new RequestListener<BaseBean<WxPayOrderInfoBean>>() {
            @Override
            public void onSuccess(Call<BaseBean<WxPayOrderInfoBean>> call, BaseBean<WxPayOrderInfoBean> response) {
                if (response.isSuccessful() && response.data != null) {
                    wxTradeNo = response.data.getTradeNo();
                    registerWXEvent();
                    new PayWX(activity).wxPay(response.data.getPartnerid(), response.data.getPrepayid(), response.data.getNoncestr(), response.data.getTimestamp() + "", response.data.getSign());
                }
                activity.dismissAll();
            }

            @Override
            public void onFailed(Call<BaseBean<WxPayOrderInfoBean>> call, ErrorResponse errorResponse) {
                activity.dismissAll();
            }
        });
    }

    @Override
    public void onABCPay() {
        activity.showProgressDialog();
        this.payWay = PayHelper.PAY_TYPE_ABC;
//        Net.abcPay(requestParams, new RequestListener<BaseBean<ABCPayBean>>() {
//            @Override
//            public void onSuccess(Call<BaseBean<ABCPayBean>> call, BaseBean<ABCPayBean> response) {
//                setAbcInfo(response.data);
//                payPop.payABC(response.data);
//                activity.dismissAll();
//            }
//
//            @Override
//            public void onFailed(Call<BaseBean<ABCPayBean>> call, ErrorResponse errorResponse) {
//                activity.dismissAll();
//            }
//        });
    }

    @Override
    public void onAliPayResult(String code, String message) {
        aliPayResultCode = code;
        if ("6001".equals(code)) {//订单已取消
            String msg = activity.getString(com.tl.commonlibrary.R.string.pay_canceled);
            UIUtils.showToast(msg);
            return;
        }
        if (aliPayBean != null) {
            activity.showProgressDialog(false);
            requestAliPayResult();
        } else {
            if (resultListener != null) {
                resultListener.onPayFailed(PayHelper.PAY_TYPE_ALI, code, message);
            }
            clearPayWay();
        }
    }

    @Override
    public void onWXPayResult(String code, String message) {
        wxPayResultCode = code;
        if ("-2".equals(code)) {
            String msg = activity.getString(com.tl.commonlibrary.R.string.pay_canceled);
            UIUtils.showToast(msg);
            return;
        }
        if ((!"".equals(wxTradeNo))) {
            activity.showProgressDialog();
            requestWXPayResult();
        } else {
            if (resultListener != null) {
                resultListener.onPayFailed(PayHelper.PAY_TYPE_WX, code, message);
            }
            clearPayWay();
        }
    }

    @Override
    public void onABCPayResult(String code, String message) {
//        abcPayResultCode = code;
//        if ("9999".equals(code)) {//支付未完成
//            String msg = activity.getString(com.tl.commonlibrary.R.string.pay_canceled);
//            UIUtils.showToast(msg);
//            return;
//        }
//        final ABCPayBean abcPayBean = getAbcInfo();
//        if (abcPayBean != null) {
//            activity.showProgressDialog(false);
//            requestABCPayResult();
//        } else {
//            if (resultListener != null) {
//                resultListener.onPayFailed(PayHelper.PAY_TYPE_ABC, code, message);
//            }
//        clearPayWay();
//        }
    }

    private void clearPayWay() {
        payWay = Integer.MIN_VALUE;
    }

    /**
     * 从服务器获取阿里支付的结果
     */
    private void requestAliPayResult() {
        Net.aliPayResult(aliPayBean.getOrderNo(), new RequestListener<BaseBean<AliPayResultBean>>() {
            @Override
            public void onSuccess(Call<BaseBean<AliPayResultBean>> call, BaseBean<AliPayResultBean> response) {
                if (response.isSuccessful() && response.data != null && response.data.success()) {
                    if (resultListener != null) {
                        String msg = activity.getString(com.tl.commonlibrary.R.string.pay_success);
                        UIUtils.showToast(msg);
                        Message message = Message.obtain();
                        message.obj = response.data;
                        resultListener.onPaySuccess(PayHelper.PAY_TYPE_ALI, message);
                    }
                    clearPayWay();
                    activity.dismissAll();
                } else {
                    //服务器端尚未同步到第三方支付返回的结果
                    reLoadResult();
                }
            }

            @Override
            public void onFailed(Call<BaseBean<AliPayResultBean>> call, ErrorResponse errorResponse) {
                if (aliPayNativeSuccess(aliPayResultCode)) {
                    reLoadResult();
                } else {
                    if (resultListener != null) {
                        resultListener.onPayFailed(PayHelper.PAY_TYPE_ALI, aliPayResultCode, activity.getString(com.tl.commonlibrary.R.string.pay_failed));
                    }
                    clearPayWay();
                    activity.dismissAll();
                }
            }
        });
    }

    private void reLoadResult() {
        if (timer.getCount() < 3) {
            timer.start();
        } else {
            // TODO: 2017/9/21 0021 弹出支付成功但没有返回结果的提示框
            new PayExceptionDialog(activity).show();
            if (resultListener != null) {
                resultListener.onPayFailed(PayHelper.PAY_TYPE_ALI, aliPayResultCode, activity.getString(com.tl.commonlibrary.R.string.pay_failed));
            }
            clearPayWay();
            activity.dismissAll();
        }
    }

    /**
     * 从服务器获取微信支付的结果
     */
    private void requestWXPayResult() {
//        Net.wechatPayResult(payWay, wxTradeNo, new RequestListener<BaseBean>() {
//            @Override
//            public void onSuccess(Call<BaseBean> call, BaseBean response) {
//                if (response.isSuccessful()) {
//                    if (resultListener != null) {
//                        String msg = activity.getString(com.tl.commonlibrary.R.string.pay_success);
//                        UIUtils.showToast(msg);
//                        resultListener.onPaySuccess(PayHelper.PAY_TYPE_WX);
//                    }
//        clearPayWay();
//                }
//                activity.dismissAll();
//            }
//
//            @Override
//            public void onFailed(Call<BaseBean> call, ErrorResponse errorResponse) {
//                //服务器端尚未同步到第三方支付返回的结果
//                if (errorResponse.businessFailed() && wxPayNativeSuccess(wxPayResultCode)) {
//                    if (timer.getCount() < 3) {
//                        timer.start();
//                    } else {
//                        // 弹出支付成功但没有返回结果的提示框
//                        new PayExceptionDialog(activity).show();
//                        if (resultListener != null) {
//                            resultListener.onPayFailed(PayHelper.PAY_TYPE_WX, wxPayResultCode, activity.getString(com.tl.commonlibrary.R.string.pay_failed));
//                        }
//        clearPayWay();
//                        activity.dismissAll();
//                    }
//                } else {
//                    if (resultListener != null) {
//                        resultListener.onPayFailed(PayHelper.PAY_TYPE_WX, wxPayResultCode, activity.getString(com.tl.commonlibrary.R.string.pay_failed));
//                    }
//        clearPayWay();
//                    activity.dismissAll();
//                }
//            }
//        });
    }

    /**
     * 从服务器获取农行支付的结果
     */
    private void requestABCPayResult() {
//        Net.abcPayResult(getAbcInfo().getOrderId(), new RequestListener<BaseBean<ABCPayResultBean>>() {
//            @Override
//            public void onSuccess(Call<BaseBean<ABCPayResultBean>> call, BaseBean<ABCPayResultBean> response) {
//                if (response.isSuccessful()) {
//                    if (resultListener != null) {
//                        String msg = activity.getString(com.tl.commonlibrary.R.string.pay_success);
//                        UIUtils.showToast(msg);
//                        resultListener.onPaySuccess(PayHelper.PAY_TYPE_ABC);
//                    }
//        clearPayWay();
//                }
//                activity.dismissAll();
//            }
//
//            @Override
//            public void onFailed(Call<BaseBean<ABCPayResultBean>> call, ErrorResponse errorResponse) {
//                //服务器端尚未同步到第三方支付返回的结果
//                if (errorResponse.businessFailed() && aliPayNativeSuccess(abcPayResultCode)) {
//                    if (timer.getCount() < 3) {
//                        timer.start();
//                    } else {
//                        // 弹出支付成功但没有返回结果的提示框
//                        new PayExceptionDialog(activity).show();
//                        if (resultListener != null) {
//                            resultListener.onPayFailed(PayHelper.PAY_TYPE_ABC, abcPayResultCode, activity.getString(com.tl.commonlibrary.R.string.pay_failed));
//                        }
//        clearPayWay();
//                        activity.dismissAll();
//                    }
//                } else {
//                    if (resultListener != null) {
//                        resultListener.onPayFailed(PayHelper.PAY_TYPE_ABC, abcPayResultCode, activity.getString(com.tl.commonlibrary.R.string.pay_failed));
//                    }

//        clearPayWay();
//                    activity.dismissAll();
//                }
//            }
//        });
    }

    /**
     * 本地返回的阿里支付结果是否成功
     *
     * @param nativeCode
     * @return
     */
    public boolean aliPayNativeSuccess(String nativeCode) {
        return PAY_ALI_SUCCESS.equals(nativeCode);
    }

    public boolean wxPayNativeSuccess(String nativeCode) {
        return PAY_WX_SUCCESS.equals(nativeCode);
    }

    @Override
    public void onTick(long millisUntilFinished) {

    }

    @Override
    public void onFinish() {
        switch (payWay) {
            case PayHelper.PAY_TYPE_WX:
                requestWXPayResult();
                break;
            case PayHelper.PAY_TYPE_ALI:
                requestAliPayResult();
                break;
            case PayHelper.PAY_TYPE_ABC:
                requestABCPayResult();
                break;
            default:
                break;
        }
    }

    public void registerWXEvent() {
        EventUtil.register(this);
    }

    public void unRegisterWXEvent() {
        EventUtil.unRegister(this);
    }


}
